package org.edu.eece262.taskshare;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;

import org.edu.eece262.taskshare.Messages.Group;
import org.edu.eece262.taskshare.Messages.GroupMember;

import com.google.gson.Gson;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class Groups extends Activity {
	
	TabHost tabs;
	ListView lvGroups;
	ArrayAdapter<String> aaGroups;
	ArrayList<String> aGroups;
	ListView lvPendingGroups;
	ArrayAdapter<String> aaPendingGroups;
	ArrayList<String> aPendingGroups;
	ListView lvRequests;
	ArrayAdapter<String> aaRequests;
	ArrayList<String> aResuests;
	ArrayList<String> isAskingToJoin;
	HashMap<String, String> hmGroup;
	HashMap<String, String> hmUser;
	HashMap<String, Integer> hmPosition;
	Button bAdd;
	EditText etSearch;
	int dialogType;
	
	public static class DialogTypes {
    	public static final int GROUPS = 0;
    	public static final int REQUESTED = 1;
    	public static final int PENDING = 2; 
    }
	
	Gson gson;
	public static final String PREFS_NAME = "TASKSHARELOGIN";
	
	private static final int NEW_GROUP = Menu.FIRST;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.contacts);
		
		gson = new Gson();
		
		update();
		
		tabs = (TabHost)this.findViewById(R.id.tabhostContacts);
		tabs.setup();
		TabHost.TabSpec tab = tabs.newTabSpec("Requests");
		tab.setContent(R.id.llRequests);
		tab.setIndicator("Requests", null);
		tabs.addTab(tab);
		tab = tabs.newTabSpec("Groups");
		tab.setContent(R.id.llContacts);
		tab.setIndicator("Groups", null);
		tabs.addTab(tab);
		tab = tabs.newTabSpec("Pending");
		tab.setContent(R.id.llPending);
		tab.setIndicator("Pending", null);
		tabs.addTab(tab);
		tabs.setCurrentTab(0);
		
		lvGroups = (ListView) findViewById(R.id.lvContacts);
		aaGroups = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, aGroups);
		lvGroups.setAdapter(aaGroups);
		lvGroups.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View v, int position,
					long arg3) {
				dialogType = DialogTypes.GROUPS;
				showDialog(position);
			}
		});
		
		lvPendingGroups = (ListView) findViewById(R.id.lvPending);
		aaPendingGroups = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, aPendingGroups);
		lvPendingGroups.setAdapter(aaPendingGroups);
		lvPendingGroups.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
					};
		});
		lvRequests = (ListView) findViewById(R.id.lvRequests);
		aaRequests = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, aResuests);
		lvRequests.setAdapter(aaRequests);
		lvRequests.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View v, int position,
					long arg3) {
					showRequest(aResuests.get(position));
				};
		});
		
		bAdd = (Button) findViewById(R.id.bSearchContacts);
		etSearch = (EditText) findViewById(R.id.etNewTask);
		
		bAdd.setText("Join");
		
		bAdd.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				final LinkedList<Group> llResults = HTTPHelp.getActivityHTTPHelp().searchGroups(etSearch.getText().toString(), getApplicationContext());
				LinkedList<String> llGroups = new LinkedList<String>();
				for(int i = 0; i < llResults.size(); i++) {
					llGroups.add(llResults.get(i).getGroupName());
				}
				showGroupList(llGroups, llResults);
			}
		});
	}
	
	private void showRequest(final String request) {
		if(isAskingToJoin.contains(request)) {
			this.setTheme(android.R.style.Theme_Black);
			new AlertDialog.Builder(this).setTitle("Allow user to join?")
			.setMessage("Group: " + hmGroup.get(request) + "\nUser: " + hmUser.get(request))
			.setPositiveButton("Allow", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					Cursor group = GroupDBAdapter.getGroupDBA(getApplicationContext()).getGroupWithName(hmGroup.get(request));
					group.moveToFirst();
					LinkedList<Messages.GroupMember> members = GroupDBAdapter.groupMembersFromCursor(group);
					members.get(hmPosition.get(request)).setGroupMemberStatus(GroupMember.StatusType.ACTIVE);
					HTTPHelp.getActivityHTTPHelp().updateGroup(group.getString(GroupDBAdapter.NAME_COLUMN), 
							group.getString(GroupDBAdapter.OWNER_COLUMN), 
							members, getApplicationContext());
					update();
					notifyUpdate();
					dialog.dismiss();
				}
			}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			}).create().show();
			this.setTheme(android.R.style.Theme_Light);
		} else {
			Cursor group = GroupDBAdapter.getGroupDBA(getApplicationContext()).getGroupWithName(request);
			group.moveToFirst();
			this.setTheme(android.R.style.Theme_Black);
			new AlertDialog.Builder(this).setTitle("Join group?")
			.setMessage("Name: " + request + "\nOwner: " + group.getString(GroupDBAdapter.OWNER_COLUMN))
			.setPositiveButton("Accept", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					HTTPHelp.getActivityHTTPHelp().joinGroup(request, getApplicationContext());
					update();
					notifyUpdate();
					dialog.dismiss();
				}
			}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			}).create().show();
			this.setTheme(android.R.style.Theme_Light);
		}
	}
	
	private void showGroupList(LinkedList<String> llGroups, LinkedList<Group> llResults) {
		ListView lvResults = new ListView(this);
		final ArrayAdapter<String> aaGroups = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, llGroups);
		final LinkedList<Group> results = llResults;
		lvResults.setAdapter(aaGroups);
		this.setTheme(android.R.style.Theme_Black);
		new AlertDialog.Builder(this).setTitle("Search Results").setSingleChoiceItems(aaGroups, -1, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				showGroup(results.get(which));
			}
		}).create().show();
		this.setTheme(android.R.style.Theme_Light);
	}
	
	public boolean showGroup(final Messages.Group group) {
		this.setTheme(android.R.style.Theme_Black);
		new AlertDialog.Builder(this).setTitle("Request to join?")
		.setMessage("Name: " + group.getGroupName() + "\nOwner: " + group.getOwner())
		.setPositiveButton("Request", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				HTTPHelp.getActivityHTTPHelp().joinGroup(group.getGroupName(), getApplicationContext());
				update();
				notifyUpdate();
				dialog.dismiss();
			}
		}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		}).create().show();
		this.setTheme(android.R.style.Theme_Light);
		return true;
	}
	
	private void update() {
		aGroups = new ArrayList<String>();
		aPendingGroups = new ArrayList<String>();
		aResuests = new ArrayList<String>();
		
		isAskingToJoin = new ArrayList<String>();
		hmGroup = new HashMap<String, String>();
		hmUser = new HashMap<String, String>();
		hmPosition = new HashMap<String, Integer>();
		
		Cursor c = GroupDBAdapter.getGroupDBA(getApplicationContext()).getAllEntries();
		
		SharedPreferences settings = getApplicationContext().getSharedPreferences(PREFS_NAME, 0);
		String user = settings.getString("user", "");
		
		if(c.getCount() > 0) {
			c.moveToFirst();
			while(!c.isAfterLast()) {
				LinkedList<Messages.GroupMember> members = GroupDBAdapter.groupMembersFromCursor(c);
				for(int i = 0; i < members.size(); i++) {
					if(members.get(i).getGroupMemberUser().equals(user)) {
						switch(members.get(i).getGroupMemberStatus()) {
							case Messages.GroupMember.StatusType.ACTIVE:
								aGroups.add(c.getString(GroupDBAdapter.NAME_COLUMN));
								break;
							case Messages.GroupMember.StatusType.REQUESTED:
								aResuests.add(c.getString(GroupDBAdapter.NAME_COLUMN));
								break;
							case Messages.GroupMember.StatusType.WAITING:
								aPendingGroups.add(c.getString(GroupDBAdapter.NAME_COLUMN));
								break;
						}
					} else if(c.getString(GroupDBAdapter.OWNER_COLUMN).equals(user)) {
						switch(members.get(i).getGroupMemberStatus()) {
							case Messages.GroupMember.StatusType.REQUESTED:
								aPendingGroups.add(c.getString(GroupDBAdapter.NAME_COLUMN)+ " - " + members.get(i).getGroupMemberUser());
								break;
							case Messages.GroupMember.StatusType.WAITING:
								String message = c.getString(GroupDBAdapter.NAME_COLUMN)+ " - " + members.get(i).getGroupMemberUser();
								aResuests.add(message);
								isAskingToJoin.add(message);
								hmGroup.put(message, c.getString(GroupDBAdapter.NAME_COLUMN));
								hmUser.put(message, members.get(i).getGroupMemberUser());
								hmPosition.put(message, i);
								break;
						}
					}
				}
				c.moveToNext();
			}
		}
	}
	
	void notifyUpdate() {
		aaGroups.notifyDataSetChanged();
		lvGroups.invalidate();
		aaPendingGroups.notifyDataSetChanged();
		lvPendingGroups.invalidate();
		aaRequests.notifyDataSetChanged();
		lvRequests.invalidate();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		boolean result = super.onCreateOptionsMenu(menu);
		menu.add(0, NEW_GROUP, 1, "New Group");
		return result;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case NEW_GROUP:
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				final EditText tmp;
				builder.setMessage("   Create Group   ")
				.setView(tmp = new EditText(getApplicationContext()))
				.setPositiveButton("Create", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								if (tmp.getText().toString().equalsIgnoreCase(""))
								{
									makeToast("Groups must have names.");
								} else {
									SharedPreferences user = getApplicationContext().getSharedPreferences(PREFS_NAME, 0);
									startActivity(new Intent(getApplicationContext(),CreateGroup.class)
									.putExtra("group_name", tmp.getText().toString())
									.putExtra("owner", user.getString("user","")));
									
									dialog.dismiss();
								}
							}
						}).setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.dismiss();
							}
						});
				AlertDialog alert = builder.create();
				alert.show();
				break;
				
			default:
				break;
		}

		return super.onOptionsItemSelected(item);
	}
	
	public void InviteContacts(int id) {
		SharedPreferences user = getApplicationContext().getSharedPreferences(PREFS_NAME, 0);
		startActivity(new Intent(getApplicationContext(),InviteContacts.class)
		.putExtra("group_name", aaGroups.getItem(id))
		.putExtra("owner", user.getString("user","")));
	}
	
	protected Dialog onCreateDialog(final int id) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		
		switch(dialogType)
		{
		case DialogTypes.GROUPS:
			LayoutInflater inflater = (LayoutInflater) getApplicationContext()
			.getSystemService(LAYOUT_INFLATER_SERVICE);

			View layout = inflater.inflate(R.layout.groupoptions,
					(ViewGroup) findViewById(R.id.goRoot));
		
			Button bInviteContacts = (Button) layout.findViewById(R.id.bInviteContacts);
			
			bInviteContacts.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					InviteContacts(id);
					dismissDialog(id);
				}
			});
			
			builder.setMessage("     Group Options     ").setView(layout)
					.setNegativeButton("Cancel",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									dialog.dismiss();
						}
					});
			break;
		case DialogTypes.PENDING:
			break;
		case DialogTypes.REQUESTED:
			break;
		default:
		}
		
		AlertDialog alert = builder.create();
		return alert;
	}
		
		void makeToast(String alert) {
			Toast.makeText(getApplicationContext(), alert, Toast.LENGTH_SHORT)
			.show();
		}
	}